import { createSlice } from '@reduxjs/toolkit' //状态管理工具库
import request from '@/utils/request' //拦截器
import { setToken, getToken, delToken } from '@/utils/auth' //Token处理

export const login = createSlice({
  name: 'login',
  initialState: {
    token: getToken() || '',
  },
  reducers: {
    setTokenRdd(state, action) {
      state.token = action.payload
    },
    delTokenRd(state) {
      state.token = ''
    },
  },
})
export const { setTokenRdd, delTokenRd } = login.actions

export function loginAction(values) {
  return async (dispatch) => {
    const { data } = await request.post('/authorizations', values)
    //console.log('登录：', data.token)
    dispatch(setTokenRdd(data.token))
    setToken(data.token)
    // localStorage.setItem('geek-token', data.token)
  }
}
export function logoutAction() {
  return (dispatch) => {
    dispatch(delTokenRd())
    delToken()
  }
}

export default login.reducer //导出action函数(组件中可以dispatch(action函数)触发reducer更新状态)
